# BSD3.0
# cili@163.com


from socket import gethostbyname,gethostname
from pathlib import Path
import threading
import tkinter as tk
from tkinter import ttk
import webserver
import search_handler


import spider

class GUI:
    def __init__(self, root):
        self.root = root
        self.port = tk.IntVar(value=8080)
        self.ip = gethostbyname(gethostname())
        self.server = webserver.MyTCPServer(self.port.get(), search_handler.SearchHandler)
        self.server.start()
        self.port.set(self.server.port)

        self.root.title("简易搜索系统")
        self.root.resizable(False, False)

        self.pane = tk.PanedWindow(root, orient="horizontal")
        self.pane.pack(expand=True, fill="both")

        self.search_panel = ttk.Frame(self.pane)
        self.gen_server_gui(self.search_panel)
        self.pane.add(self.search_panel)
        self.search_panel.grid(row=0, column=0, sticky="nsew", pady=5)

        if spider.ver():
            separator = ttk.Separator(self.pane, orient="horizontal")
            self.pane.add(separator)
            separator.grid(row=1, column=0, sticky="ew", pady=5)
            self.spider_panel = ttk.Frame(self.pane)
            self.gen_spider_gui(self.spider_panel)
            self.pane.add(self.spider_panel)
            self.spider_panel.grid(row=2, column=0, sticky="nsew")

        self.center_windows()
        self.url_text.focus()
        self.url_text.select_range(0, tk.END)

    def gen_server_gui(self,panel):
        self.ip_label = ttk.Label(panel, text="IP地址：", anchor='e')
        self.ip_label.grid(row=0, column=0, sticky="e", padx=5, pady=5)
        self.ip_text = ttk.Label(panel, width=30, text=self.ip)
        self.ip_text.grid(row=0, column=1, sticky="w", padx=5, pady=5)

        self.port_label = ttk.Label(panel, text="服务端口：", anchor='e')
        self.port_label.grid(row=1, column=0, sticky="e", padx=5, pady=5)
        self.port_text = ttk.Label(panel, textvariable=self.port, width=30)
        self.port_text.grid(row=1, column=1, sticky="w", padx=5, pady=5)

        self.status_label = ttk.Label(panel, text="访问地址：", anchor='e')
        self.status_label.grid(row=2, column=0, sticky="e", padx=5, pady=5)

        self.url_text = ttk.Entry(panel, width=40)
        self.url_text.insert(tk.END, f"http://{self.ip}:{self.port.get()}")
        self.url_text.state(['readonly'])
        self.url_text.grid(row=2, column=1, sticky="w", padx=5,pady=5)

    def gen_spider_gui(self, panel):

        self.spider_label = ttk.Label(panel, text="需要自动获取的网址：")
        self.spider_label.grid(row=4, column=0, sticky="w", padx=5, pady=5)
        self.spider_text = ttk.Entry(panel, width=50)
        with open('default.txt', 'r') as f:
            data = f.readlines()
        self.spider_text.insert(0,data[0])
        self.spider_text.grid(row=5, column=0, sticky="w", padx=5, pady=5)
        self.spider_button = ttk.Button(panel, text="启动网络爬虫", command=self.start_spider)
        self.spider_button.grid(row=5, column=2, padx=10, sticky="w", pady=5)

    def center_windows(self):
        self.root.update()
        screen_width = self.root.winfo_screenwidth()
        screen_height = self.root.winfo_screenheight()
        window_width = self.root.winfo_width()
        window_height = self.root.winfo_height()
        x = int((screen_width / 2) - (window_width / 2))
        y = int((screen_height / 2) - (window_height / 2))
        self.root.geometry(f'+{x}+{y}')

    def start_spider(self):
        spider_url = self.spider_text.get().strip()
        if not spider_url.startswith('http'): spider_url = f'https://{spider_url}'
        if spider_url:
            spider_thread = threading.Thread(target=self.run_spider, args=(spider_url,))
            spider_thread.start()
            self.spider_button.config(text="正在获取信息")
            self.spider_button.config(state='disabled')

    def run_spider(self, spider_url):
        spider.crawl(spider_url)
        self.spider_button.config(text="启动网络爬虫")
        self.spider_button.config(state='normal')

if __name__ == "__main__":
    p = Path('web')
    if not p.exists():p.mkdir()
    root = tk.Tk()
    gui = GUI(root)
    root.mainloop()